package dao;

import entity.OrderDetail;
import utils.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class OrderDetailDao {
    public void createOrderDetail(int orderId, int productId, int quantity, double price) {
        String sql = "INSERT INTO order_details (order_id, product_id, quantity, price) VALUES (?, ?, ?, ?)";
        try (Connection conn = JDBCUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            // 设置占位符参数
            pstmt.setInt(1, orderId);
            pstmt.setInt(2, productId);
            pstmt.setInt(3, quantity);
            pstmt.setDouble(4, price);

            // 执行插入操作
            int rowsAffected = pstmt.executeUpdate();
            if (rowsAffected > 0) {
                System.out.println("订单详情插入成功！");
            } else {
                System.out.println("订单详情插入失败！");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            // 可以选择记录日志或抛出运行时异常
            throw new RuntimeException("创建订单详情时发生错误", e);
        }
    }

    public List<OrderDetail> getOrderDetailsByOrderId(int orderId) {
        List<OrderDetail> orderDetails = new ArrayList<>();
        String sql = "SELECT \n" +
                "    od.product_id, \n" +
                "    od.quantity, \n" +
                "    od.price, \n" +
                "    p.PRODUCT_NAME  \n" +
                "FROM \n" +
                "    order_details od \n" +
                "INNER JOIN \n" +
                "    products p \n" +
                "ON \n" +
                "    od.product_id = p.PRODUCT_ID \n" +
                "WHERE \n" +
                "    od.order_id = ?\n";

        try (Connection connection = JDBCUtil.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(sql)) {

            // 设置查询参数
            preparedStatement.setInt(1, orderId);

            // 执行查询
            try (ResultSet resultSet = preparedStatement.executeQuery()) {
                while (resultSet.next()) {
                    // 创建 OrderDetail 对象并填充数据
                    OrderDetail detail = new OrderDetail();
                    detail.setProductName(resultSet.getString("product_name"));
                    detail.setQuantity(resultSet.getInt("quantity"));
                    detail.setPrice(resultSet.getBigDecimal("price"));
                    detail.setProductId(resultSet.getInt("product_id"));
                    // 添加到列表
                    orderDetails.add(detail);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();

        }
        return orderDetails;
    }

}
